package com.huaxinkai.mobile.util.sqlmanage;


import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
/**
 * sql.xml  获取xml中sql类
 * @author liuzh
 * @date 2017年1月11日下午10:34:08
 */
public class SqlServer {
	/**
	 * 静态doc
	 */
	private static Document sqlxml = null;
	/**
	 * 静态加载XML文件
	 */
	static {
		SAXReader reader = new SAXReader(); 
		File file = new File("src/main/resources/sql/sql.xml");
		try {
			sqlxml = reader.read(new File(file.getAbsolutePath()));
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 遍历所有节点获取sql
	 * @param root
	 * @param key
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	private static String findKey(Element root,String key){
		Iterator it = root.elementIterator();
		String sql = null;
		while (it.hasNext()) {
			Element child = (Element) it.next();
			if(child.getName().equals( key )){
				sql = child.getStringValue();
				break;
			}else{
				sql =  findKey(child, key);
			}
		}
		return sql;
	}
	/**
	 * 通过节点名获取sql
	 * @param key
	 * @return
	 */
	public static String getSql(String key){
		Element root = SqlServer.sqlxml.getRootElement();
		return findKey(root,key);
	}
	
	
	@Test
	public void dom4jMyTest(){
		String key = "group_list";
		String value = getSql(key);
		System.out.println("获取到的sql：" + value );
	}
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Test
	public void dom4jTest(){
		
		Element root = SqlServer.sqlxml.getRootElement();
		System.out.println("root："+ root.getPath());
		// 通过element对象的elementIterator方法获取迭代器
		Iterator it = root.elementIterator();
		// 遍历迭代器，获取根节点中的信息
		while (it.hasNext()) {
			System.out.println("=====开始遍历=====");
			Element book = (Element) it.next();
			// 获取book的属性名以及 属性值
			List<Attribute> bookAttrs = book.attributes();
			for (Attribute attr : bookAttrs) {
				System.out.println("属性名：" + attr.getName() + "--属性值："
						+ attr.getValue());
			}
			Iterator itt = book.elementIterator();
			while (itt.hasNext()) {
				Element bookChild = (Element) itt.next();
				System.out.println("节点名：" + bookChild.getName() + "--节点值：" + bookChild.getStringValue());
			}
			System.out.println("=====结束遍历=====");
		}
		
	}
}
